package com.huntmobi.springsecuritydemo.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huntmobi.springsecuritydemo.base.http.Request;
import com.huntmobi.springsecuritydemo.base.http.Response;
import com.huntmobi.springsecuritydemo.base.pojo.SysMenu;
import com.huntmobi.springsecuritydemo.base.util.TreeUtils;
import com.huntmobi.springsecuritydemo.base.dto.sysmenu.Add;
import com.huntmobi.springsecuritydemo.base.dto.sysmenu.Update;
import com.huntmobi.springsecuritydemo.service.ISysMenuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 邹智敏
 * @since 2020-08-11
 */
@RestController
@RequestMapping("/sysMenu")
public class SysMenuController {

    @Autowired
    private ISysMenuService iSysMenuService;

    @GetMapping("/findByPage")
    public Request findByPage(String id){
        return Response.success(TreeUtils.getMenu(iSysMenuService.findByPage(id)));
    }

    @PostMapping("/add")
    public Request add(@Valid @RequestBody Add add) {
        SysMenu sysMenu = new SysMenu();
        BeanUtils.copyProperties(add, sysMenu);
        if (iSysMenuService.save(sysMenu)) {
            return Response.success();
        }
        return Response.error();
    }

    @PostMapping("/update")
    public Request update(@Valid @RequestBody Update update) {
        SysMenu sysMenu = new SysMenu();
        BeanUtils.copyProperties(update, sysMenu);
        if (iSysMenuService.updateById(sysMenu)) {
            return Response.success();
        }
        return Response.error();
    }

    @GetMapping("/delete/{id}")
    public Request delete(@PathVariable String id) {
        if (iSysMenuService.remove(new QueryWrapper<SysMenu>().lambda().eq(SysMenu::getId, id))) {
            //删除子级菜单
            iSysMenuService.remove(new QueryWrapper<SysMenu>().lambda().eq(SysMenu::getParentId,id));
            return Response.success();
        }
        return Response.error();
    }

    @GetMapping("/leftSideMenu")
    public Request leftSideMenu(String roleName) {

        return Response.success(TreeUtils.getMenu(iSysMenuService.leftSideMenu(roleName)));
    }

}

